package dragon.social.core.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: Leo
 * @Date: 2020/3/16 22:27
 * 认证成功处理器
 * SavedRequestAwareAuthenticationSuccessHandler是spring默认的成功处理器
 */
@Component("AuthenticationSuccessHandler")
public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    ObjectMapper objectMapper;

    String returnType = "JSON";
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        //返回json数据
        if(returnType.equals("JSON")){
            String json = objectMapper.writeValueAsString(authentication);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(json);
        }
        //使用默认的方式，即跳转到登录前想访问的url
        else {
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
